package com.heima.movement.service.impl;

import com.heima.models.movement.pojos.Likes;
import com.heima.models.movement.pojos.Movement;
import com.heima.models.movement.pojos.MovementComment;
import com.heima.movement.mapper.LikesMapper;
import com.heima.movement.mapper.MovementCommentMapper;
import com.heima.movement.mapper.MovementMapper;

import java.time.LocalDateTime;

/**
 * 当一段代码，想用异步线程的方式去执行，那么就需要给这个类继承Runnable，重写run方法
 * 在run方法中实现具体逻辑
 */
public class LikeThread implements Runnable {

    private LikesMapper likesMapper;

    private MovementCommentMapper movementCommentMapper;

    private MovementMapper movementMapper;

    private String targetId;

    private Integer type;

    /**
     * 你不可以直接在线程类里面注入Bean，如果用到一些bean，那么就需要通过构造方法的方式传递进来
     * 如果你需要从外面传递一些参数进来，那么也要通过构造方法
     * @param movementMapper
     * @param movementCommentMapper
     * @param likesMapper
     * @param targetId
     * @param type
     */
    public LikeThread(MovementMapper movementMapper,
                      MovementCommentMapper movementCommentMapper,
                      LikesMapper likesMapper, String targetId, Integer type) {
        this.likesMapper = likesMapper;
        this.movementMapper = movementMapper;
        this.movementCommentMapper = movementCommentMapper;
        this.targetId = targetId;
        this.type = type;
    }

    /**
     * 注意：run方法没有返回值
     * 所以你没有办法处理成功返回或者失败返回
     */
    @Override
    public void run() {
        // 2. like记录表加一条记录
        Likes likes = new Likes();
        likes.setTargetId(targetId);
        likes.setType(type);
        likes.setUserId(0);
        likes.setCreatedTime(LocalDateTime.now());
        int insertResult = likesMapper.insert(likes);
        if (insertResult != 1) {
            return;
        }

        // 3. 动态表点赞数+1
        // 根据type去判断，如果是1，就更新动态，如果是2，就更新评论
        if (type == 1) {
            Movement movement = movementMapper.selectById(targetId);
            if (movement != null) {
                Integer likesCount = movement.getLikes();
                movement.setLikes(likesCount + 1);
                int updateResult = movementMapper.updateById(movement);
                if (updateResult != 1) {
                    // 需要触发前面一个MySQl写入操作的回滚
                    throw new RuntimeException("点赞更新失败");
                }
            }
        } else {
            MovementComment movementComment = movementCommentMapper.selectById(targetId);
            if (movementComment != null) {
                Integer likesCount = movementComment.getLikes();
                movementComment.setLikes(likesCount + 1);
                int commentResult = movementCommentMapper.updateById(movementComment);
                if (commentResult != 1) {
                    throw new RuntimeException("评论点赞数更新失败");
                }
            }
        }
    }
}
